import {userLogin,fetchUserInfo} from '@/request/UserRuquest'
import {getObjectInStorage,getStringInStorage,setItemInStorage,removeItemInStorage,isUserInfoExpired} from '@/utils/localStorageUtils'
const state = {
  zrId:'',
  zrNickname:'',
  zrAvatar:'',
  role:'role_no_login',
  token:'',           //authorization
  expiredTime:null,   //mills
}
const mutations={
  SET_ID:(state,zrId)=>{
    state.zrId = zrId
  },
  SET_NICKNAME:(state,zrNickname)=>{
    state.zrNickname = zrNickname
  },
  SET_AVATAR:(state,zrAvatar)=>{
    state.zrAvatar = zrAvatar
  },
  SET_ROLE:(state,role)=>{
    state.role = role
  },
  SET_TOKEN:(state,token)=>{
    state.token = token
  },
  SET_EXPIRED_TIME:(state,expiredTime)=>{
    state.expiredTime = expiredTime
}

}
const actions={
  login({commit},userInfo){
    const {account,password} = userInfo
    return new Promise((resolve,reject)=>{
      userLogin(account,password).then(userBaseInfo=>{
        storeUserInfo({commit,userBaseInfo})
        setItemInStorage('user',JSON.stringify(userBaseInfo))
        resolve({
          message:'登陆成功'
        })
      }).catch(error=>{
        reject(error)
      })
    })
  },

  getUserInfo({commit,state}){
    return new Promise((resolve,reject)=>{
      fetchUserInfo(state.zrId)
          .then(userBaseInfo=>{
            storeUserInfo({commit,userBaseInfo})
            setItemInStorage('user',JSON.stringify(userBaseInfo))
          }).catch(error=>{
            reject(error)
      })
    })
  },
  logout({commit,state,dispatch}){
    return new Promise((resolve,reject)=>{
      abolishUserInfo(commit)
      removeItemInStorage('user')

      //重置缓存的页面和访问页面  todo
      dispatch('tagsView/delAllViews',null,{root:true})
      resolve()
    })
  }
}

function storeUserInfo({commit,userBaseInfo}){
  commit('SET_ID',userBaseInfo.zrId)
  commit('SET_NICKNAME',userBaseInfo.zrNickname)
  commit('SET_AVATAR',userBaseInfo.zrAvatar)
  commit('SET_ROLE',userBaseInfo.role)
  commit('SET_TOKEN',userBaseInfo.token)
  commit('SET_EXPIRED_TIME',userBaseInfo.expiredTime)
}

function initUserInfo({commit}){
  let userBaseInfo = getObjectInStorage('user',{
    zrId:'',
    zrNickname:'',
    zrAvatar:'',
    role:'role_no_login',
    token:'',
    expiredTime:0,
  })
  storeUserInfo({commit,userBaseInfo})

}
function abolishUserInfo({commit}){
  commit('SET_ID','')
  commit('SET_NICKNAME','')
  commit('SET_AVATAR','')
  commit('SET_ROLE','')
  commit('SET_TOKEN','')
  commit('SET_EXPIRED_TIME',new Date()/1000)

}

export default {
  namespaced:true,
  state,
  mutations,
  actions
}